/*
* Created by WangRuoNan On 2018/12/26.
* */
import React from "react";
import {connect} from 'react-redux'
import {Col, Row, Button, Icon, message, Modal, Input, Tabs, Tree, Radio} from 'antd';
const {TextArea} = Input;
const TreeNode = Tree.TreeNode;
import TitleAndContentService from 'components/template/title-and-content-i18n/title-and-content-i18n.service'
import BraftEditor from "braft-editor";
import 'braft-editor/dist/braft.css'
import {messages} from "share/common";
import UploadFile from "components/upload";
import config from "config";
import 'styles/components/template/title-and-content/title-and-content.scss'
import errorMessage from "share/errorMessage";

class TitleAndContentI18n extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      content: '',
      activeKey: "",
      lanList: [],
      i18n: props.i18n,
      linkDocVisible: false,
      linkDocTitle: '',
      linkDocId: '',
      prodMenuList: [], //已发布到正式环境到目录列表
    }
  }


  componentWillMount() {
    this.lanListTransform();
  }

  componentWillReceiveProps(nextProps) {
    if(this.props !== nextProps){
      this.setState({
        i18n: nextProps.i18n,
      }, () => {
        this.i18nTransform();
      });
    }
  };

  lanListTransform = () => {
    const {languageTabs, languageList} = this.props;
    let lanList = [];
    if(languageTabs && languageTabs.length){
      lanList = languageTabs;
    }else{
      languageList.map(item => {
        lanList.push({key: item.code.toLowerCase(), tab: item.value})
      });
    }
    this.setState({
      lanList,
      activeKey: lanList[0].key
    }, () => {
      this.i18nTransform();
    });
  };



  //处理i18n
  i18nTransform = () => {
    const {activeKey, lanList, i18n} = this.state;
    const {contentType} = this.props;
    let titleArr = [];
    let contentArr = [];
    i18n.title.map(item => {
      titleArr.push(item.language.toLowerCase());
    });
    i18n.content.map(item => {
      contentArr.push(item.language.toLowerCase());
    });
    lanList.map(item => {
      if(titleArr.indexOf(item.key) === -1){
        i18n.title.push({language: item.key, value: ""});
      }
      if(contentArr.indexOf(item.key) === -1){
        i18n.content.push({language: item.key, value: ""});
      }
    });
    let content = i18n.content.filter(item => item.language.toLowerCase() === activeKey)[0].value;
    contentType === "editor" && this.editorInstance.setContent(content, 'html');
    this.setState({
      i18n,
      content,
    });
  };

  onActiveKeyChange = (e) => {
    const {i18n} = this.state;
    const {contentType} = this.props;
    let content = i18n.content.filter(item => item.language.toLowerCase() === e.target.value)[0].value;
    contentType === "editor" && this.editorInstance.setContent(content, 'html');
    this.setState({
      activeKey: e.target.value,
      content,
    });
  };

  //根据租户主语言获取 i18n 里面的多语言
  getMainLanguage = (i18n) => {
    let obj = {};
    for(let key in i18n){
      obj[key] = _getValByCode(this.props.language.code, i18n[key]);
    }
    return obj;
    function _getValByCode(code, arr) {
      let val = '';
      arr.map(item => {
        if(item.language.toLowerCase() === code.toLowerCase()){
          val = item.value;
        }
      });
      return val;
    }
  }
  //题目改变时
  onTitleChange = (e) => {
    const {activeKey, i18n} = this.state;
    i18n.title.filter(item => item.language.toLowerCase() === activeKey)[0].value = e.target.value;
    i18n.title.map(item => {
      if(item.language === "zh_tw"){
        item.language = "zh_TW"
      }
    });
    this.setState({
      i18n
    }, () => {
      let i18n = this.state.i18n;
      this.props.onI18nChange(i18n,this.getMainLanguage(i18n));
    })
  };

  //富文本中上传图片
  handleImageUpload = (param) => {
    const formData = new FormData();
    formData.append('attachmentType', 'OTHER');
    formData.append('file', param.file);
    TitleAndContentService.handleImageUpload(formData).then(res => {
      param.success({url: res.data.fileURL})
    }).catch(err => {
      errorMessage(err.response);
      param.error();
      message.error(messages('components.key767')/*图片上传失败*/)
    })
  };

  //富文本内容改变时
  handleContentChange = (content) => {
    const {i18n, activeKey} = this.state;
    //以下是为了在移动端防止图片过大而无法完全显示的问题
    let img_arr = content.match(/<img.*?>/g);
    let newImg = "";
    img_arr && img_arr.map(img => {
      if (img.match(/width="auto"/) && img.match(/height="auto"/)) {
        newImg = img.replace(/width="auto"/, '');
        newImg = img.replace(/height="auto"/, '');
        newImg = img.replace(/width:auto;height:auto;/, '');
      }
      content = content.replace(img, newImg)
    });

    //以下是为了解决 富文本编辑器会自动篡改<a>标签的href 的问题
    let aArr = content.match(/<a.*?>/g);
    aArr && aArr.length && aArr.map(item => {
      let initHref = item.match(/href="(.*?)".*?/g)[0];
      let hrefArr = initHref.split("/");
      if (hrefArr[1] !== "main") {
        let len = hrefArr.length;
        let newItem = "";
        hrefArr.map((href, index) => {
          if (href === "main") {
            hrefArr = (hrefArr.slice(index, len + 1)).join("/");
            newItem = item.replace(initHref, `href="/${hrefArr} target="_blank"`);
          }
        });
        content = content.replace(item, newItem);
      }
    });

    //以下是因为移动端无法正确显示<em>和<i>，因此加上css属性实现斜体
    content = content.replace(/<em>/g, '<em style="font-style: italic">');
    content = content.replace(/<i>/g, '<i style="font-style: italic">');
    this.setState({
      content
    });
    i18n.content.filter(item => item.language.toLowerCase() === activeKey)[0].value = content;
    i18n.content.map(item => {
      if(item.language === "zh_tw"){
        item.language = "zh_TW"
      }
    });
    this.setState({
      i18n
    }, () => {
      let i18n = this.state.i18n;
      this.props.onI18nChange(i18n,this.getMainLanguage(i18n));
    })
  };

  //上传文件
  handleFileUpload = (fileList) => {
    let content = this.state.content;
    fileList.map(item => {
      if (item.response.fileURL.endsWith("jpg") || item.response.fileURL.endsWith("png") || item.response.fileURL.endsWith("jpeg")) {
        content += `<img src="${item.response.fileURL}"/> `;
      } else {
        content += `<a href="${item.response.fileURL}" target="">${item.name}</a> `;
      }
    });
    this.editorInstance.setContent(content, 'html');
    this.handleContentChange(content);
    this.setState({visible: false})
  };

  //渲染目录树
  renderTree = (data) => {
    return data.map(item => {
      return (
        <TreeNode key={item.id} title={item.docTitle}>
          {item.children && item.children.length ? this.renderTree(item.children) : ''}
        </TreeNode>
      )
    })
  };

  //添加链接文档
  addLinkDoc = () => {
    const {linkDocTitle, linkDocId} = this.state;
    if (!linkDocTitle) {
      message.error('请输入链接文字')
    } else if (!linkDocId) {
      message.error('请选择链接的文档')
    } else {
      let docContent = this.state.content;
      docContent += `<a class="link-doc" href="/main/help-center-user/doc/${linkDocId}" target="_blank">${linkDocTitle}</a>`;
      this.editorInstance.setContent(docContent, 'html');
      this.handleContentChange(docContent);
      this.setState({linkDocVisible: false})
    }
  };
  /*--链接帮助文档--*/


  handleValueChange = (e) => {
    const {i18n, activeKey} = this.state;
    i18n.content.filter(item => item.language.toLowerCase() === activeKey)[0].value = e.target.value;
    i18n.content.map(item => {
      if(item.language === "zh_tw"){
        item.language = "zh_TW"
      }
    });
    this.setState({
      i18n
    }, () => {
      let i18n = this.state.i18n;
      this.props.onI18nChange(i18n,this.getMainLanguage(i18n));
    })
  };

  translateLanguage = (language) => {
    let tab = '';
    switch (language) {
      case '简体中文': tab = messages('enterprise-manage.key99'/*简体中文*/); break;
      case '英文': tab = messages('setting.key1211'/*英文*/); break;
      case '繁体中文': tab = messages('components.key834')/*繁体中文*/; break;
      case '日语': tab = messages('help-center-admin.key3'/*日语*/); break;
    }
    return tab;
  };

  render() {
    const {visible, activeKey, i18n, linkDocVisible, linkDocTitle, linkDocId, prodMenuList, lanList} = this.state;
    const {disabled, needTitle, contentType} = this.props;
    const controls = [
      'undo', 'redo', 'split', 'text-align', 'font-size', 'font-family', 'line-height', 'text-color',
      'bold', 'italic', 'underline', 'strike-through', 'superscript',
      'subscript', 'split', 'headings', 'list_ul', 'list_ol',
      'blockquote', 'code', 'split', 'link', 'split', 'media'
    ];
    const extendControls = [{
      type: 'button',
      text: <Icon type="file-add"/>,
      hoverTitle: messages('components.key492')/*上传文件*/,
      className: 'file-add',
      onClick: () => this.setState({visible: true})
    },
    ];
    return (
      <div className={'title-and-content'}>
        <Radio.Group onChange={this.onActiveKeyChange} value={activeKey.toLowerCase()} style={{marginBottom: 20}}>
          {
            lanList.length && lanList.map(item => {
              return <Radio.Button value={item.key} key={item.key.toLowerCase()}>{this.translateLanguage(item.tab)}</Radio.Button>
            })
          }
        </Radio.Group>
        {
          needTitle &&
          <Row style={{marginBottom: 20}}>
            <Col span={24}>
              <Input placeholder={messages('common.please.input')/*请输入*/}
                     value={i18n.title && i18n.title.length ? i18n.title.filter(item => item.language.toLowerCase() === activeKey)[0].value : ""}
                     onChange={this.onTitleChange}
                     disabled={disabled}/>
            </Col>
          </Row>
        }
        {
          contentType === "editor" &&
          <Row>
            <Col span={24}>
              <BraftEditor height={400}
                           controls={controls}
                           language={this.props.language.code}
                           contentFormat="html"
                           initialContent={i18n.content && i18n.content.length ? i18n.content.filter(item => item.language.toLowerCase() === activeKey)[0].value : ""}
                           extendControls={extendControls}
                           media={{
                             image: true,
                             video: false,
                             audio: false,
                             externalMedias: {
                               image: false,
                               video: false,
                               audio: false
                             },
                             uploadFn: this.handleImageUpload
                           }}
                           ref={instance => this.editorInstance = instance}
                           onChange={this.handleContentChange}
                           disabled={disabled}/>
            </Col>
          </Row>
        }
        {
          contentType === "textArea" &&
          <Row>
            <Col span={24}>
                <TextArea
                  value={i18n.content && i18n.content.length ? i18n.content.filter(item => item.language.toLowerCase() === activeKey)[0].value : ""}
                  onChange={this.handleValueChange}
                  style={{height: 300}}
                  disabled={disabled}/>
            </Col>
          </Row>
        }
        {visible && (
          <Modal title={messages('components.key492')/*上传文件*/}
                 visible={visible}
                 onCancel={() => this.setState({visible: false})}
                 footer={<Button onClick={() => this.setState({visible: false})}>
                   取消
                 </Button>}>
            <UploadFile uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                        attachmentType="OTHER"
                        extensionName="rar, zip, doc, docx, pdf, jpg, jpeg, png, bmp, xlsx, gif"
                        fileNum={1}
                        needAllResponse={true}
                        uploadHandle={this.handleFileUpload}/>
          </Modal>
        )}
        <Modal title="选择链接文档"
               visible={linkDocVisible}
               bodyStyle={{maxHeight: 'calc(100vh - 150px)', overflow: 'auto'}}
               onOk={this.addLinkDoc}
               onCancel={() => this.setState({linkDocVisible: false})}>
          <Row style={{lineHeight: '32px', paddingBottom: 10, borderBottom: '1px solid #e8e8e8'}}>
            <Col span={4}>链接文字：</Col>
            <Col span={20}>
              <Input placeholder={messages('common.please.input')/*请输入*/} value={linkDocTitle}
                     onChange={e => this.setState({linkDocTitle: e.target.value})}/>
            </Col>
          </Row>
          <Tree className="draggable-tree"
                selectedKeys={[linkDocId]}
                onSelect={(key, e) => this.setState({linkDocId: key[0], linkDocTitle: e.selectedNodes[0].props.title})}>
            {this.renderTree(prodMenuList)}
          </Tree>
        </Modal>
      </div>
    )
  }
}

TitleAndContentI18n.contextTypes = {
  router: React.PropTypes.object,
};

TitleAndContentI18n.prototypes = {
  needTitle: React.PropTypes.bool,//是否需要标题,默认为true
  disabled: React.PropTypes.bool,//是否禁用,默认为false
  onI18nChange: React.PropTypes.func,
  contentType: React.PropTypes.string,
  /*
  * onI18nChange的注释：
  * 名称或题目内容发生改变时,回传内容为:
  * i18n:{title: [{language: "zh_cn", value: ""}],content: [{language: "zh_cn", value: ""}]}
  * */
  languageTabs: React.PropTypes.array,
  /*
  * languageTabs的注释：
  * 不同语言tabPanes, 不传的时候取redux的state.login.languageList; 格式为
  * languageTabs：[{key: 'zh_cn', tab: "中文"}, {key: 'en', tab: "英文"}]
  * */

  i18n: React.PropTypes.object.isRequired,
  /*
  * i18n的注释：
  * 名称和标题的多语言，，格式为
  * i18n: {title: [{language: "zh_cn", value: ""}, language: "en", value: ""],
  * content: [{language: "zh_cn", value: ""}, language: "en", value: ""]}
  * */
};

TitleAndContentI18n.defaultProps = {
  needTitle: true,
  disabled: false,
  languageTabs: [],
  i18n: {title: [], content:[]},
  contentType: "editor", //内容区域默认是富文本编辑器，可选为textArea
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    languageList: state.login.languageList,
  }
}

export default connect(mapStateToProps)(TitleAndContentI18n)
